﻿#region Copyright & License

// Copyright © 2012 - 2014 François Chabot, Yves Dierick
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// 
// http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#endregion

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using Be.Stateless.BizTalk.Dsl.RuleEngine;
using Be.Stateless.Linq.Extensions;
using Microsoft.BizTalk.Operations;
using NUnit.Framework;

namespace Be.Stateless.BizTalk.Unit.Process
{
	public abstract class ProcessFixture
	{
		protected ProcessFixture()
		{
			// compute values of ProcessNameAttribute-qualified members so that one can use them in unit test assertions

			// only assemblies referencing the target assembly must be taken into account
			var targetReferencedAssemblyName = typeof(ProcessNameAttribute).Assembly.GetName().FullName;

			// ReSharper disable ReturnValueOfPureMethodIsNotUsed
			// eagerly compute process names, whose values will be written back to members (that's the wanted side-effect)
			GetType().Assembly.GetReferencedAssemblies()
				.Select(a => Assembly.Load(a.FullName))
				.Where(a => a.GetReferencedAssemblies().Any(an => an.FullName == targetReferencedAssemblyName))
				.Select(a => a.GetTypes())
				.Select(ts => ProcessNameAttribute.GetProcessNames(ts))
				.ToArray();
			// ReSharper restore ReturnValueOfPureMethodIsNotUsed
		}

		protected DateTime StartTime { get; private set; }

		protected MessageBoxServiceInstance[] UncompletedBizTalkServiceInstances
		{
			get { return GetRunningOrSuspendedServiceInstances(new BizTalkOperations()).ToArray(); }
		}

		[SetUp]
		protected void ProcessFixtureSetup()
		{
			StartTime = DateTime.UtcNow;
		}

		[TearDown]
		protected void ProcessFixtureTearDown()
		{
			TerminateUncompletedBizTalkServiceInstances();
		}

		/// <summary>
		/// Terminate all BizTalk service instances that are still running or that have been suspended.
		/// </summary>
		protected void TerminateUncompletedBizTalkServiceInstances()
		{
			var bizTalkOperations = new BizTalkOperations();
			GetRunningOrSuspendedServiceInstances(bizTalkOperations)
				.Select(i => new { i.ID, Status = bizTalkOperations.TerminateInstance(i.ID) })
				.Where(i => i.Status != CompletionStatus.Succeeded)
				.Each(i => Trace.TraceWarning("Could not terminate the BizTalk service instance with ID {0}", i.ID));
		}

		private IEnumerable<MessageBoxServiceInstance> GetRunningOrSuspendedServiceInstances(BizTalkOperations bizTalkOperations)
		{
			return bizTalkOperations
				.GetServiceInstances().OfType<MessageBoxServiceInstance>()
				.Where(i => (i.InstanceStatus & (InstanceStatus.RunningAll | InstanceStatus.SuspendedAll)) != InstanceStatus.None);
		}
	}
}
